package com.melody.service.impl;

import cn.hutool.Hutool;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.melody.common.component.SmsComponent;
import com.melody.entry.Result;
import com.melody.entry.UserInfo;
import com.melody.model.dto.UserRegisterDto;
import com.melody.model.dto.UserSaveDto;
import com.melody.model.vo.UserInfoVo;
import com.melody.model.vo.UserLogin;
import com.melody.service.UserInfoService;
import com.melody.mapper.UserInfoMapper;
import com.melody.utils.JwtUtil;
import com.melody.utils.RedisUtil;
import com.melody.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author zxz
* @description 针对表【user_info(用户信息表)】的数据库操作Service实现
* @createDate 2025-05-09 10:31:18
*/
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo>
    implements UserInfoService{


    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private UserInfoMapper userInfoMapper;

    /**
     * 用户注册
     * @param userRegisterDto
     * @return
     */
    @Override
    public Result<String> userRegister(UserRegisterDto userRegisterDto) {
        // 1.判断信息是否完全+手机号是否存在
        if (userRegisterDto == null || userRegisterDto.getUserName() == null || userRegisterDto.getPhone() == null || userRegisterDto.getPassword() == null){
            return Result.error("请填写完整信息");
        }
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getPhone,userRegisterDto.getPhone());
        if (getOne(queryWrapper) != null){
            return Result.error("手机号已存在");
        }
        // 2.redis获取验证码
        String redisCode = redisUtil.getVerificationCode( "phone:code:"+userRegisterDto.getPhone());
        if (redisCode == null){
            return Result.error("验证码过期");
        }
        // 3.判断验证码是否正确
        if (!redisCode.equals(userRegisterDto.getCode())){
            return Result.error("验证码错误");
        }
        // 4.插入数据库语句
        UserInfo userInfo = new UserInfo();
        userInfo.setUserName(userRegisterDto.getUserName());
        userInfo.setPhone(userRegisterDto.getPhone());
        userInfo.setPassword(userRegisterDto.getPassword());
        userInfo.setType(1);
        if (save(userInfo)){
            // 5.返回token
            Map<String, Object> claims = new HashMap<>();
            claims.put("userId",userInfo.getUserId() );
            claims.put("username", userInfo.getUserName());
            // 生成JWT
            String token = JwtUtil.genToken(claims);
            return Result.success(token);
        }
        return Result.error("注册失败");
    }


    /**
     * 用户登录
     * @param userSaveDto
     * @return
     */
    @Override
    public Result<String> userLogin(UserSaveDto userSaveDto) {
//        0.验证信息是否完整
        if (userSaveDto == null || userSaveDto.getPhone() == null || userSaveDto.getPassword() == null){
            return Result.error("请填写完整信息");
        }
//        1.根据手机号查询是否存在
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getPhone,userSaveDto.getPhone());
        UserInfo userInfo = getOne(queryWrapper);
        if (userInfo == null){
            //        1.2不存在 - 注册
            return Result.error("用户不存在，请注册");
        }
//        1.1存在 - 下一步
//        2.查询密码是否正确
        if (userInfo.getPassword().equals(userSaveDto.getPassword())){
            //        2.1正确 - 返回token
            // 创建一个包含用户数据的Map
            Map<String, Object> claims = new HashMap<>();
            claims.put("userId",userInfo.getUserId() );
            claims.put("username", userInfo.getUserName());
            // 生成JWT
            String token = JwtUtil.genToken(claims);
            return Result.success(token);
        }
//        2.2不正确
        return Result.error("密码错误");
    }


    /**
     * 根据token获取用户详情
     *
     * @return
     */
    @Override
    public Result<UserInfoVo> userInfoById() {
//        1.获取token中的用户
        Map<String, Object> user = ThreadLocalUtil.get();
        Object id = user.get("userId");
//        2.数据库查询
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getUserId,id.toString());
        UserInfo userInfo = getOne(queryWrapper);
        if (userInfo != null){
            UserInfoVo userInfoVo = new UserInfoVo();
            BeanUtil.copyProperties(userInfo,userInfoVo);
            return Result.success(userInfoVo);
        }
        return Result.error("用户不存在");
    }

    /**
     * 用户删除
     * @return
     */
    @Override
    public Result<String> deleteUser() {
        //        1.获取token中的用户
        Map<String, Object> user = ThreadLocalUtil.get();
        Object id = user.get("userId");
//        2.数据库操作
        boolean b = removeById( (Integer) id);
        if (b){
            return Result.success("删除成功");
        }
        return Result.error("删除失败");
    }

    /**
     * 验证码登录
     * @param userSaveDto
     * @return
     */
    @Override
    public Result<String> codeLogin(UserSaveDto userSaveDto) {
        if (userSaveDto == null || userSaveDto.getPhone() == null || userSaveDto.getCode() == null){
            return Result.error("请填写完整信息");
        }
        //        1.根据手机号查询是否存在
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getPhone,userSaveDto.getPhone());
        UserInfo userInfo = getOne(queryWrapper);
        if (userInfo == null){
            //        1.2不存在 - 注册
            return Result.error("用户不存在，请注册");
        }
        String redisCode = redisUtil.getVerificationCode( "phone:code:"+userSaveDto.getPhone());
        if (redisCode == null){
            return Result.error("验证码过期");
        }
        if (redisCode.equals(userSaveDto.getCode())){
            // 创建一个包含用户数据的Map
            Map<String, Object> claims = new HashMap<>();
            claims.put("userId",userInfo.getUserId() );
            claims.put("username", userInfo.getUserName());
            // 生成JWT
            String token = JwtUtil.genToken(claims);
            return Result.success(token);
        }
        return Result.error("验证码错误");
    }

    /**
     * 根据id获取用户详情
     * @param userId
     * @return
     */
    @Override
    public Result<UserInfoVo> userInfoByIdid(Integer userId) {
        if (userId != null){
            LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(UserInfo::getUserId,userId);
            UserInfo userInfo = getOne(queryWrapper);
            if (userInfo != null){
                UserInfoVo userInfoVo = new UserInfoVo();
                BeanUtil.copyProperties(userInfo,userInfoVo);
                return Result.success(userInfoVo);
            }
        }
        return  Result.error("用户不存在");
    }

    /**
     * 天气项目临时借用
     * 实现登录注册
     * @param userLogin
     * @return
     */
    @Override
    public Result<String> loginOrRegister(UserLogin userLogin) {
//        查询数据库是否有该手机号
        if (userLogin.getPhone() == null||  userLogin.getPhone().equals("")){
            return Result.error("请输入手机号");
        }
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getPhone,userLogin.getPhone());
        List<UserInfo> list = list(queryWrapper);
        if (list.size() > 0){
//            有-登录
            if (userLogin.getCode() == null || userLogin.getCode().equals("")){
                return Result.error("请输入验证码");
            }
            String redisCode = redisUtil.getVerificationCode( "phone:code:"+userLogin.getPhone());
            if (redisCode == null){
                return Result.error("验证码过期");
            }
            if (redisCode.equals(userLogin.getCode())){

                // 创建一个包含用户数据的Map
                Map<String, Object> claims = new HashMap<>();
                claims.put("userId", list.get(0).getUserId() );
                claims.put("username", list.get(0).getUserName());
                // 生成JWT
                String token = JwtUtil.genToken(claims);
                return Result.success(token);
            }
        }
//       没有-注册
                UserInfo userInfo = new UserInfo();
                userInfo.setPhone(userLogin.getPhone());
                userInfo.setUserName(userLogin.getPhone());
                userInfo.setPassword(userLogin.getPhone());
                userInfoMapper.insert(userInfo);
        // 创建一个包含用户数据的Map
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", list.get(0).getUserId() );
        claims.put("username", list.get(0).getUserName());
        // 生成JWT
        String token = JwtUtil.genToken(claims);
        return Result.success(token);

    }
}




